<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\api\controller;


use app\api\lists\article\XiaoxiLists;
use app\common\model\user\User;
use EasyWeChat\OfficialAccount\Application;

/**
 * 文章管理
 * Class ArticleController
 * @package app\api\controller
 */
class XiaoxiController extends BaseApiController
{

    public function lists()
    {
        return $this->dataLists(new XiaoxiLists());

    }

    public function ceshi()
    {

        $openid = 'oqdWs6HLYWUNurbwYzSk3Fka6Jr8';
        $template_id = 'us9omVgOjXIkJHDNYwoLItdafZfu4L3ShqN5YFI9ke4';

        $data = [
            'thing2' => '你好，您有一个运输订单取消了，请及时确认！',
            'character_string8' => 'keyword1',

        ];
        $res = $this->template1($openid, $template_id, $data);
        print_r($res);

    }

    public function template1($openid, $template_id, $data, $url = '', $miniprogram = ['appid' => '', 'pagepath' => ''])
    {

        $config = [
            'app_id' => 'wxaae9936c4891bea0',
            'secret' => 'a018f583ad80711396355269aee3ae71',
            'token' => 'guoyitong13145',
            'aes_key' => '' //明文模式下为空
        ];

        $app = new Application($config);

        $api = $app->getClient();

        /*$url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb44ba13733872d8c&secret=8fa3f39e98b314155ee12b01556f46e2';
        $response = $api->get($url);*/

        $accessToken = $app->getAccessToken(); // 使用easywechat自带的方法,获取访问令牌
        $token = $accessToken->getToken(); // string
        $data = [];
        $data['thing2']['value'] = '你好，您有一个运输订单取消了，请及时确认';
        $data['character_string8']['value'] = 'dfdf';
        $template = [
            'touser' => 'oqdWs6HLYWUNurbwYzSk3Fka6Jr8',
            'template_id' => 'us9omVgOjXIkJHDNYwoLItdafZfu4L3ShqN5YFI9ke4',
            'url' => 'http://demo.sohu.com/',
            'data' => $data,

        ];
        $template = json_encode($template, true);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $token;

        $result = $this->posts($url, $template);
        if ($result['errcode'] == 0) {
            echo '发送成功';
        } else {
            echo '发送失败';


        }
    }


    public function posts(string $url, $params, array $headers = [])
    {
        $headers[] = 'Content-type: application/json';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        curl_close($ch);

        return json_decode($output, true);
    }

    /**
     * 发送HTTP请求方法
     * @param string $url 请求URL
     * @param array $params 请求参数
     * @param string $method 请求方法GET/POST
     * @param array $header 请求头
     * @param bool $multi 是否传输文件
     * @return array  $data   响应数据
     */
    function http($url, $params, $method = 'GET', $header = array(), $body = '', $multi = false)
    {
        $opts = array(
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER => $header,
        );

        /* 根据请求类型设置特定参数 */
        switch (strtoupper($method)) {
            case 'GET':
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                break;
            case 'POST':
                //判断是否传输文件
                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;

        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        return $data;
    }

    //发送微信模版消息
    public function template($openid, $template_id, $data, $url = '', $miniprogram = ['appid' => '', 'pagepath' => ''])
    {
        $config = [
            'app_id' => '',
            'secret' => '',
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];
        $app = Factory::officialAccount($config);
        return $app->template_message->send([
            'touser' => $openid,
            'template_id' => $template_id,
            'url' => $url,
            'miniprogram' => $miniprogram,
            'data' => $data,
        ]);
    }

    public function dingyue()
    {
        $parme = $this->request->post();
        $user_id = $this->userId;

        $user = (new User())->where("id", "=", $user_id)->findOrEmpty()->toArray();
        $array = $user['dingyue'] ? explode(",", $user['dingyue']) : [];

        if (in_array($parme['id'], $array)) {
            // 如果id已经在dingyue列表中，移除它
            $index = array_search($parme['id'], $array);
            array_splice($array, $index, 1);
        } else {
            // 如果id不在dingyue列表中，添加它
            $array[] = $parme['id'];
        }

        // 更新用户的dingyue列表
        $user['dingyue'] = implode(",", $array);
        (new User())->where("id", "=", $user_id)->update(['dingyue'=>$user['dingyue']]);

        return $this->success("", ['data' => 1], 1, 1);
    }


}